"""
本模块实现jwt token的认证！
"""
# =========== 导入组件 ============
from utils.base_import import *
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

import jwt
from jwt import exceptions


class MyJwtAuthentication(BaseAuthentication):

    # 重写authenticate
    def authenticate(self, request):
        # 获取token
        token = request.META.get('HTTP_TOKEN', None)
        # 获取setting中的key
        key = settings.SECRET_KEY
        # 开始认证
        try:
            payload = jwt.decode(token, key, algorithms=['HS256'])
        except exceptions.ExpiredSignatureError:
            raise AuthenticationFailed({'error': "Token已失效！"})
        except jwt.DecodeError:
            raise AuthenticationFailed({'error': "认证失败！"})
        except jwt.InvalidTokenError:
            raise AuthenticationFailed({'error': "无效的Token！"})
        except:
            raise AuthenticationFailed({'error': "未知的错误！"})



        return payload, token